package com.example.weatherpredict.ui;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.DeviceUtils;
import com.example.weatherpredict.R;
import com.example.weatherpredict.base.BaseActivity;
import com.example.weatherpredict.callback.OnItemClickListener;
import com.example.weatherpredict.databinding.ActivityMainBinding;
import com.example.weatherpredict.db.DatabaseHelper;
import com.example.weatherpredict.entity.CityBean;
import com.example.weatherpredict.entity.Weather;
import com.example.weatherpredict.service.NotificationService;
import com.example.weatherpredict.ui.SettingActivity;
import com.example.weatherpredict.ui.WeatherDetailActivity;
import com.example.weatherpredict.utils.FlickFetchr;

import java.util.ArrayList;
import java.util.List;

/**
 * HomeActivity
 * description: HomeActivity
 *
 * @author : 李承扬
 * @date : 2024/6/13
 * email : licy3051@qq.com
 */
public class HomeActivity extends BaseActivity<ActivityMainBinding> {

    public String API_KEY = "2b73e5bd89c2440f842aff2eca77ce22";

    //七天的天气详情对象
    private List<Weather.DailyBean> mItems;
    private WeatherAdapter mWeatherAdapter;

    private SQLiteDatabase mDatabase;

    private String location = "";       //记录当前的城市ID，如果有变化，需要刷新你页面
    private String temp_unit = "";
    private String unit_text = "";


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        //创建数据库
        mDatabase = new DatabaseHelper(mActivity).getWritableDatabase();

        mItems = new ArrayList<>();
        mWeatherAdapter = new WeatherAdapter(mItems);
        mViewBinding.fragmentWeatherRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mViewBinding.fragmentWeatherRecyclerView.setAdapter(mWeatherAdapter);

        mWeatherAdapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Weather.DailyBean weatherItem = mItems.get(position);
                if (DeviceUtils.isTablet()) {
                    // pad 刷新右侧内容
                    mViewBinding.padDetailDate.setText(weatherItem.fxDate);
                    mViewBinding.padDetailMaxTemp.setText(weatherItem.tempMax + unit_text);
                    mViewBinding.padDetailMinTemp.setText(weatherItem.tempMin + unit_text);
                    mViewBinding.padDetailIcon.setImageDrawable(getResources().getDrawable(getIconId(mActivity, "a" + weatherItem.iconDay)));
                    mViewBinding.padDetailHumidity.setText("Humidity: " + weatherItem.humidity + " %");
                    mViewBinding.padDetailPressure.setText("Pressure: " + weatherItem.pressure + " hPa");
                    mViewBinding.padDetailWind.setText("Wind: " + weatherItem.windSpeedDay + " km/h SE");
                    mViewBinding.padDetailDesc.setText(weatherItem.textDay);
                } else {
                    // 手机
                    Intent intent = WeatherDetailActivity.newIntent(mActivity, weatherItem);
                    startActivity(intent);
                }
            }
        });

        // 加载menu
        mViewBinding.toolbar.inflateMenu(R.menu.fragment_weather);
        mViewBinding.toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_map:
                        SharedPreferences pref = mActivity.getSharedPreferences("setting", Context.MODE_PRIVATE);
                        //调用腾讯地图  e255f161ee4f8644baf4c8f540a96533
                        Intent intent_txmap = new Intent();
                        intent_txmap.setAction(Intent.ACTION_VIEW);
                        intent_txmap.addCategory(Intent.CATEGORY_DEFAULT);

                        System.out.println("lat is :" + pref.getString("lat", "39.90498"));//纬度
                        System.out.println("lon is :" + pref.getString("lon", "116.40528"));//经度

                        intent_txmap.setData(Uri.parse("https://m.amap.com/navi/?dest=" +
                                pref.getString("lon", "116.40528") +
                                "," + pref.getString("lat", "39.90498") +
                                "&destName=" + pref.getString("city", "北京") +
                                "&hideRouteIcon=1" +
                                "&key=e255f161ee4f8644baf4c8f540a96533"));
                        startActivity(intent_txmap);
                        break;
                    case R.id.menu_home_setting:
                        Intent intent = new Intent(mActivity, SettingActivity.class);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void initListener() {

    }


    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences pref = mActivity.getSharedPreferences("setting", Context.MODE_PRIVATE);
        String city = pref.getString("city", "北京");
        String unit = pref.getString("unit", "摄氏度");
        String send = pref.getString("send", "是");
        if (city != location) {     //在重新启动页面的时候，如果地址改变了，需要刷新
            location = city;
            new FetchItemsTask().execute();  //异步执行，获取网站上的json内容
            return;
        }
        if (unit != temp_unit) {     //在重新启动页面的时候，摄氏度/华氏度改变了，需要刷新
            temp_unit = unit;
            new FetchItemsTask().execute();  //异步执行，获取网站上的json内容
            return;
        }
        if (send == "是") {
            //开启后台服务，启动定时器，发送通知消息
            NotificationService.setServiceAlarm(mActivity, true);
        } else {
            NotificationService.setServiceAlarm(mActivity, false);
        }
    }


    public class WeatherHolder extends RecyclerView.ViewHolder {

        private View mItemView;
        private Weather.DailyBean mWeatherItem;
        private TextView mItemMaxWeather;
        private TextView mItemMinWeather;
        private ImageView mItemIcon;
        private TextView mItemDate;
        private TextView mItemDesc;

        public View getItemView() {
            return mItemView;
        }

        public void setDay(String day) {
            mItemDate.setText(day);
        }

        public WeatherHolder(View itemView) {
            super(itemView);
            mItemView = itemView;
            mItemMaxWeather = (TextView) itemView.findViewById(R.id.item_max_weather);
            mItemMinWeather = (TextView) itemView.findViewById(R.id.item_min_weather);
            mItemIcon = (ImageView) itemView.findViewById(R.id.item_icon);
            mItemDate = (TextView) itemView.findViewById(R.id.item_date);
            mItemDesc = (TextView) itemView.findViewById(R.id.item_desc);
        }

        public void bindWeatherItem(Weather.DailyBean weatherItem) {
            mWeatherItem = weatherItem;
            mItemMaxWeather.setText(weatherItem.tempMax + unit_text);
            mItemMinWeather.setText(weatherItem.tempMin + unit_text);
            String icon = "a" + weatherItem.iconDay;
            int id = getIconId(mActivity, icon);
            Drawable drawable = getResources().getDrawable(id);
            mItemIcon.setImageDrawable(drawable);
            mItemDate.setText(weatherItem.fxDate);
            mItemDesc.setText(weatherItem.textDay);
        }
    }

    //获取drawable图标资源的id
    public int getIconId(Context mContext, String icon) {
        return getResources().getIdentifier(icon, "drawable", mContext.getPackageName());
    }

    private class WeatherAdapter extends RecyclerView.Adapter<WeatherHolder> {

        private OnItemClickListener mItemClickListener;
        private List<Weather.DailyBean> mWeatherList = new ArrayList<>();

        public WeatherAdapter(List<Weather.DailyBean> items) {
            mWeatherList = items;
        }

        public OnItemClickListener getItemClickListener() {
            return mItemClickListener;
        }

        public void setItemClickListener(OnItemClickListener itemClickListener) {
            mItemClickListener = itemClickListener;
        }

        public List<Weather.DailyBean> getWeatherList() {
            return mWeatherList;
        }

        public void setWeatherList(List<Weather.DailyBean> weatherList) {
            mWeatherList = weatherList;
        }

        @Override
        public int getItemCount() {
            return mWeatherList.size();
        }

        @Override
        public WeatherHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            //实例化mars_item布局
            LayoutInflater inflater = LayoutInflater.from(mActivity);
            View view = inflater.inflate(R.layout.weather_item, parent, false);
            return new WeatherHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull WeatherHolder holder, int position) {
            Weather.DailyBean weatherItem = mWeatherList.get(position);
            holder.bindWeatherItem(weatherItem);
            holder.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getItemClickListener().onItemClick(view, holder.getAdapterPosition());
                }
            });
        }
    }


    // 异步从URL获取天气对象
    private class FetchItemsTask extends AsyncTask<Void, Void, List<Weather.DailyBean>> {
        private SharedPreferences.Editor editor = mActivity.getSharedPreferences("setting", Context.MODE_PRIVATE).edit();
        private SharedPreferences pref = mActivity.getSharedPreferences("setting", Context.MODE_PRIVATE);
        private String city = pref.getString("city", "北京");
        private String unit = pref.getString("unit", "摄氏度");
        private String city_url = "https://geoapi.qweather.com/v2/city/lookup?location=" + city + "&key=" + API_KEY;


        @SuppressLint("Range")
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        protected List<Weather.DailyBean> doInBackground(Void... voids) {
            List<Weather.DailyBean> weatherItems = new ArrayList<>();
            unit_text = "°C";
            if (unit == "华氏度") {
                unit_text = "℉";
            }
            //如果没有网络连接，从数据库获取信息
            if (!isNetworkConnected(mActivity.getApplicationContext())) {
                Cursor cursor = mDatabase.query("weather", null, null, null, null, null, null);
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    Weather.DailyBean item = new Weather.DailyBean();
                    item.fxDate = (cursor.getString(cursor.getColumnIndex("date")));
                    item.tempMax = (cursor.getString(cursor.getColumnIndex("max_temp")));
                    item.tempMin = (cursor.getString(cursor.getColumnIndex("min_temp")));
                    item.textDay = (cursor.getString(cursor.getColumnIndex("text")));
                    item.humidity = (cursor.getString(cursor.getColumnIndex("humidity")));
                    item.pressure = (cursor.getString(cursor.getColumnIndex("pressure")));
                    item.windSpeedDay = (cursor.getString(cursor.getColumnIndex("wind")));
                    item.iconDay = (cursor.getString(cursor.getColumnIndex("icon")));
                    weatherItems.add(item);
                    cursor.moveToNext();
                }
                return weatherItems;
            } else {
                CityBean.LocationBean cityJson = new FlickFetchr().fetchCity(city_url);
                if (cityJson != null) {
                    // 保存城市数据到sp
                    String locationID = cityJson.id;
                    editor.putString("lat", cityJson.lat);
                    editor.putString("lon", cityJson.lon);
                    editor.commit();
                    // 构建请求连接
                    String url = "https://devapi.qweather.com/v7/weather/7d?location=" + locationID + "&key=" + API_KEY;
                    if (unit == "华氏度") {
                        url += "&unit=i";
                    }
                    weatherItems = new FlickFetchr().fetchItems(url);
                    //删除原来的数据库，将获取的数据放入数据库
                    mDatabase.execSQL("drop table weather");
                    mDatabase.execSQL("create table weather (_id INTEGER PRIMARY KEY AUTOINCREMENT,date text,max_temp text,min_temp text,text text,humidity text,pressure text,wind text,icon text)");
                    for (int i = 0; i < weatherItems.size(); i++) {
                        Weather.DailyBean item = weatherItems.get(i);
                        ContentValues values = new ContentValues();
                        values.put("date", item.fxDate);
                        values.put("max_temp", item.tempMax);
                        values.put("min_temp", item.tempMin);
                        values.put("text", item.textDay);
                        values.put("humidity", item.humidity);
                        values.put("pressure", item.pressure);
                        values.put("wind", item.windSpeedDay);
                        values.put("icon", item.iconDay);
                        mDatabase.insert("weather", null, values);
                    }
                }
                return weatherItems;
            }
        }

        @Override
        protected void onPostExecute(List<Weather.DailyBean> weatherItems) {
            mItems = weatherItems;
            if (mItems.isEmpty()) {
                return;
            }

            //实现今天天气部分的UI
            Weather.DailyBean weatherItem = mItems.get(0);
            mViewBinding.todayTime.setText("Today, " + location);
            mViewBinding.todayTemp.setText(weatherItem.tempMin + unit_text + " ~ " + weatherItem.tempMax + unit_text);
            mViewBinding.todayIconDesc.setText(weatherItem.textDay);
            String icon = "a" + weatherItem.iconDay;
            int id = getIconId(mActivity, icon);
            if (id > 0) {
                Drawable drawable = getResources().getDrawable(id);
                mViewBinding.todayIcon.setImageDrawable(drawable);
            }
            //实现recyclerview部分的UI
            mWeatherAdapter.setWeatherList(mItems);
            mWeatherAdapter.notifyDataSetChanged();

            //如果是ipad，就手动更新详情页面
            if (DeviceUtils.isTablet()) {
                mViewBinding.padDetailDate.setText(weatherItem.fxDate);
                mViewBinding.padDetailMaxTemp.setText(weatherItem.tempMax + unit_text);
                mViewBinding.padDetailMinTemp.setText(weatherItem.tempMin + unit_text);
                mViewBinding.padDetailIcon.setImageDrawable(getResources().getDrawable(getIconId(mActivity, "a" + weatherItem.iconDay)));
                mViewBinding.padDetailHumidity.setText("Humidity: " + weatherItem.humidity + " %");
                mViewBinding.padDetailPressure.setText("Pressure: " + weatherItem.pressure + " hPa");
                mViewBinding.padDetailWind.setText("Wind: " + weatherItem.windSpeedDay + " km/h SE");
                mViewBinding.padDetailDesc.setText(weatherItem.textDay);
            }
        }
    }

    //判断网络是否连接
    @RequiresApi(api = Build.VERSION_CODES.M)
    public boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean isNetworkAvailable = cm.getActiveNetwork() != null;
        boolean isNetworkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();
        return isNetworkConnected;
    }
}
